import axios from "axios";
import { Toast, Notify } from "vant";
import router from "@/router/index";
import { getToken } from "@/utils/auth";
import loadingIcon from '@/assets/images/loading.gif'
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000
});
service.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = getToken() || null;
    if (!config.loading) {
      Toast.loading({
        icon: loadingIcon,
        duration: 0,
        forbidClick: true,
        message: "",
        className: "loading-icon"
      });
    }
    return config;
  },
  (error) => {
    Toast.clear();
    Promise.reject(error);
  }
);
service.interceptors.response.use(
  (response) => {
    Toast.clear();
    const { data } = response;
    if (typeof response.data !== "object") {
      Notify({ type: "danger", message: "服务端错误" });
      return Promise.reject(data);
    }
    if (data.code != 200) {
      if (data.msg) Toast.fail(data.msg);
      if (data.code == 401) {
        //未登录
        router.push("/login");
        return;
      }
      return Promise.reject(data.msg);
    }
    return Promise.resolve(data);
  },
  (error) => {
    Toast.clear();
    return Promise.reject(error);
  }
);
export function post(url, ...config) {
  return service.post(url, ...config);
}
export function put(url, ...config) {
  return service.put(url, ...config);
}
export function del(url, params, config) {
  return service.delete(url, {
    params,
    ...config
  });
}
export function get(url, params, config) {
  return service.get(url, {
    params,
    ...config
  });
}
